package com.peng.rpc.registry;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import com.peng.rpc.loadBalance.LoadBalance;
import com.peng.rpc.util.NacosUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 用于实现服务发现、负载均衡的中间类
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/3/5 23:04
 */
@Slf4j
public class NacosServiceDiscovery implements ServiceDiscovery{

    private LoadBalance loadBalance;

    public NacosServiceDiscovery(LoadBalance loadBalance) {
        this.loadBalance = loadBalance;
    }

    @Override
    public InetSocketAddress lookupService(String serviceName) {
        try {
            List<Instance> instances = NacosUtil.getAllInstances(serviceName);
            if (instances.size() == 0) {
                throw new RpcException(RpcError.SERVICE_NOT_FOUND);
            }
            Instance instance = loadBalance.select(instances);
            return new InetSocketAddress(instance.getIp(), instance.getPort());
        } catch (NacosException e) {
            log.error("查找服务：{}失败:{}", serviceName, e.getMessage());
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
    }
}
